package com.mzj.saas.mservice.smartlock.service.tianwanghulian;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mzj.saas.commons.HttpUtils;
import com.mzj.saas.commons.ResultBean;
import com.mzj.saas.mservice.lock.Repository.*;
import com.mzj.saas.mservice.lock.entity.*;
import com.mzj.saas.mservice.smartlock.vo.DevMacStateVO;
import com.mzj.saas.mservice.smartlock.vo.SkynetInternetsVO;
import com.mzj.saas.mservice.smartlock.vo.SmartLockVO;
import com.mzj.saas.redis.RedisService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 天网互联-智能锁事件处理
 *
 * @author hp
 */
@Slf4j
@Service
public class FourEventHandleService {

    @Autowired
    private LockOpenLogRepository lockOpenLogRepository;
    @Autowired
    private LockAlarmRepository lockAlarmRepository;
    @Autowired
    private SmartLockRepository smartLockRepository;
    @Autowired
    private SmartLockAuthRepository smartLockAuthRepository;
    @Autowired
    private SmartLockPwdRepository smartLockPwdRepository;
    @Autowired
    private RedisService redisService;
    /**
     * 注册-锁绑定商户
     * @param number 设备编号
     * @param brandId 设备类型
     * @return
     * @author shun
     * @date 2023年3月9日
     */
    public ResultBean<String> event(String number, Long brandId){
        log.info("天王互联, 锁绑定商户, imei={}, brandId={}", number, brandId);
        if(StringUtils.isEmpty(number)){
            log.info("锁绑定商户失败，设备类型或编号为空，number={}, brandId={}", brandId,number);
            return ResultBean.failedResultOfParamWithMsg("锁绑定商户失败，设备类型或编号为空");
        }
        return ResultBean.successfulResult(number);
    }

    /**
     * 密码统一处理
     * @param pwd 密码
     * @param vo 锁实体
     * @param id 锁id
     * @return
     * @author shun
     */
    public ResultBean<String> TimedPassword(SmartLockVO vo, SmartLockPwd pwd, Long id) {
         log.info("锁实体, 锁id,密码 vo={}, pwd={},id={}", vo, pwd,id);
        //SmartLockPwd identification = smartLockPwdRepository.identification(pwd.getLockId());
        String token = redisService.getToken();
        Map<String,Object> hashMap=new HashMap<String,Object>();
        Map<String,Object> map=new HashMap<String,Object>();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String sDate=sdf.format(pwd.getAuthTime());
        String format = sdf.format(pwd.getStartTime());
        Map<String,Object> maps=new HashMap<String,Object>();
        maps.put("deviceNum",vo.getSn());
        String deviceNum = HttpUtils.httpClientGet("https://paas.locksuiyi.com/deviceManagement/api/permanentPassword.do", token, maps);
        JSONObject jsonObject = JSON.parseObject(deviceNum);
        JSONArray data =  (JSONArray)jsonObject.get("data");
        int size = data.size();
        List<Object> list=new ArrayList<>();
        Optional<SmartLockAuth> authOpt = smartLockAuthRepository.findById(pwd.getLockAuthId());
        SmartLockAuth smartLockAuth = authOpt.get();
        Snowflake snowflake = new Snowflake(1L,1L);
        String uuid = snowflake.nextIdStr();
        smartLockAuth.setIdentification(uuid);
        smartLockAuthRepository.setIdentification(uuid,smartLockAuth.getId());
        if(pwd.getAuthType()==1){
            if(size<17){
                map.put("identification",size+1);
            }
            map.put("password",vo.getPassword());
            list.add(map);
            hashMap.put("deviceNum",vo.getSn());
            hashMap.put("passwordList",list);
            String s = HttpUtils.httpClientPost("https://paas.locksuiyi.com/deviceManagement/api/permanentPassword.do", JSON.toJSONString(hashMap), token);
            return ResultBean.successfulResult(JSON.toJSONString(s));
        }
        if(pwd.getAuthType()==2){
            if(size<17){
                map.put("identification",size+1);
            }
            map.put("password",vo.getPassword());
            map.put("startTime",sDate);
            map.put("endTime",format);
            hashMap.put("deviceNum",vo.getSn());
            hashMap.put("passwordList",JSON.toJSONString(map));
            //HttpUtils.httpClientDelete("https://paas.locksuiyi.com/deviceManagement//api/temporaryPassword.do","",token);
            String s =HttpUtils.httpClientPost("https://paas.locksuiyi.com/deviceManagement/api/temporaryPassword.do",JSON.toJSONString(hashMap),token);
            return ResultBean.successfulResult(JSON.toJSONString(s));
        }
        if(pwd.getAuthType()==3){
            if(size<17){
                map.put("identification",uuid);
            }
            map.put("password",vo.getPassword());
            map.put("startTime",sDate);
            map.put("endTime",format);
            hashMap.put("deviceNum",vo.getSn());
            hashMap.put("passwordList",JSON.toJSONString(map));
            String s =HttpUtils.httpClientPost("https://paas.locksuiyi.com/deviceManagement/api/temporaryPassword.do",JSON.toJSONString(hashMap),token);
            return ResultBean.successfulResult(JSON.toJSONString(s));
        }
        return null;
    }

    /**
     * 天网互联清空设备
     * @param mac 设备号
     * @param brandId 锁id
     * @return
     * @author shun
     * @date 2023年3月12日
     */
    public ResultBean<String> delete(String mac, Long brandId) {
        log.info("设备号, 锁id  mac={}, brandId={}", mac, brandId);
        String token = redisService.getToken();
        Map<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("deviceNum",mac);
        //按锁编号查询临时密码
        String proTem = HttpUtils.httpClientGet("https://paas.locksuiyi.com/deviceManagement/api/temporaryPassword.do", token, hashMap);
        JSONArray data = JSON.parseArray(JSON.toJSONString(JSON.parseObject(proTem).get("data")));
        if(data.size()>0){
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("deviceNum",mac);
            List<String> list=new ArrayList<>();
            for (int i = 0; i < data.size(); i++) {
                list.add(data.getJSONObject(i).get("identification").toString());
            }
            map.put("identifications",list);
            //删除临时密码
            String s = HttpUtils.httpClientDelete("https://paas.locksuiyi.com/deviceManagement/api/temporaryPassword.do", JSON.toJSONString(map), token);
            log.info("删除临时密码  s={}", s);
        }
        //按锁编号查询永久密码
        String permanent = HttpUtils.httpClientGet("https://paas.locksuiyi.com/deviceManagement/api/permanentPassword.do", token, hashMap);
        JSONArray jsonArray = JSON.parseArray(JSON.toJSONString(JSON.parseObject(permanent).get("data")));
        if(jsonArray.size()>0){
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("deviceNum",mac);
            List<String> list=new ArrayList<>();
            for (int i = 0; i < data.size(); i++) {
                list.add(jsonArray.getJSONObject(i).get("identification").toString());
            }
            map.put("identifications",list);
            //删除永久密码
            String s = HttpUtils.httpClientDelete("https://paas.locksuiyi.com/deviceManagement/api/permanentPassword.do", JSON.toJSONString(map), token);
            log.info("删除永久密码  s={}", s);
        }
        //按锁编号查询蓝牙权限数据
        String bluetooth = HttpUtils.httpClientGet("https://paas.locksuiyi.com/deviceManagement/api/bluetooth/unlockAuthority.do", token, hashMap);
        JSONArray bluetoothData = JSON.parseArray(JSON.toJSONString(JSON.parseObject(bluetooth).get("data")));
        if(bluetoothData.size()>0){
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("deviceNum",mac);
            List<String> list=new ArrayList<>();
            for (int i = 0; i < bluetoothData.size(); i++) {
                list.add(bluetoothData.getJSONObject(i).get("mobile").toString());
            }
            map.put("identifications",list);
            //删除蓝牙授权
            String s = HttpUtils.httpClientDelete("https://paas.locksuiyi.com/deviceManagement/api/bluetooth/unlockAuthority.do", JSON.toJSONString(map), token);
            log.info("删除蓝牙授权  s={}", s);
        }
        return ResultBean.successfulResult("成功");
    }
    /**
     * 天网互联添加门卡
     * @return
     * @author shun
     */
    @SneakyThrows
    public ResultBean<String> doorCard(SmartLockVO vo, SmartLockCard smartLockCard, Long brandId) {
        String token = redisService.getToken();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar cal = Calendar.getInstance();
        Date date = new Date();
        String sDate = sdf.format(date);  //开始时间
        HashMap<String, Object> hashMap = new HashMap<>();
        String cardNumber = smartLockCard.getCardNumber();
        hashMap.put("startTime",sDate);
        if(smartLockCard.getType()==1){ //身份证
            String format = String.format("%08X", Long.valueOf(smartLockCard.getCardNumber()));
            hashMap.put("cardNum",format);
            hashMap.put("cardType","1");
        }
        if(smartLockCard.getType()==2){ //cpu
            String hex= Integer.toHexString(Math.toIntExact(Long.parseLong(smartLockCard.getCardNumber())));
            hashMap.put("cardNum",hex);
            hashMap.put("cardType","0");
        }
        hashMap.put("deviceNum",vo.getSn());
        hashMap.put("identification",smartLockCard.getCardId());
        Optional<SmartLockAuth> authOpt = smartLockAuthRepository.findById(smartLockCard.getLockAuthId());
        SmartLockAuth smartLockAuth = authOpt.get();
        Snowflake snowflake = new Snowflake(1L,1L);
        String uuid = snowflake.nextIdStr();
        smartLockAuth.setIdentification(uuid);
        smartLockAuthRepository.setIdentification(uuid,smartLockAuth.getId());
        if(smartLockCard.getAuthType()==1){
            cal.setTime(date);
            cal.add(Calendar.YEAR, 10);// 年
            date = cal.getTime();
            String dates = sdf.format(date);
            hashMap.put("endTime",dates);
        }
        if(smartLockCard.getAuthType()==2){
            cal.setTime(date);
            cal.add(Calendar.HOUR, 24);// 24小时制
            date = cal.getTime();
            String dates = sdf.format(date);
            hashMap.put("endTime",dates);
        }
        String s = HttpUtils.httpClientPost("https://paas.locksuiyi.com/deviceManagement/api/singleIdentity.do", JSON.toJSONString(hashMap), token);
        log.info("天网互联添加门卡  s={}", s);
        return ResultBean.successfulResult("成功");
    }
    /**
     * 天网互联查询智能锁列表
     * @return
     * @author shun
     */
    @SneakyThrows
    public ResultBean<DevMacStateVO> deviceList(String id, Long brandId) {
        String token = redisService.getToken();
        HashMap<String, Object> hashMap = new HashMap<>();
        DevMacStateVO data = new DevMacStateVO();
        hashMap.put("pageNum","1");
        hashMap.put("pageSize","10");
        hashMap.put("deviceNum",id);
        String s = HttpUtils.httpClientGet("https://paas.locksuiyi.com/deviceManagement/api/deviceList.do", token, hashMap);
        Object battery = JSON.parseObject(JSON.parseObject(JSON.parseObject(s).get("data").toString()).getJSONArray("list").get(0).toString()).get("battery");
        data.setBattery((Integer) battery);
        Object connStatus = JSON.parseObject(JSON.parseObject(JSON.parseObject(s).get("data").toString()).getJSONArray("list").get(0).toString()).get("connStatus");
        data.setState((Integer) connStatus);
        log.info("天网互联查询智能锁列表  s={}", s);
        return ResultBean.successfulResult(data);
    }
    /**
     * 天网互联添告警
     * @return4
     * @author shun
     */
    @SneakyThrows
    public ResultBean<String> SkynetInternetWarn(SkynetInternetsVO skynetInternet) {
        SkynetInternetsVO data = skynetInternet.getData();
        if (ObjectUtil.isEmpty(data)) {
            List<SkynetInternetsVO> list = JSON.parseArray(JSONObject.toJSONString(skynetInternet.getDatas()), SkynetInternetsVO.class);
            for (SkynetInternetsVO skynetInternetsVO : list) {
                skynetInternetsVO.setProductType(skynetInternet.getProductType());
                skynetInternetsVO.setType(skynetInternet.getType());
            }
            return this.warnOperateList(list);
        } else {
            data.setProductType(skynetInternet.getProductType());
            data.setType(skynetInternet.getType());
            return this.warnOperate(data);
        }
    }


    @SneakyThrows
    public ResultBean<String> warnOperateList(List<SkynetInternetsVO> list) {
        LockAlarm lockAlarm = new LockAlarm();
        for (SkynetInternetsVO skynetInternetsVO : list) {
            SmartLock smartLock = smartLockRepository.getSmartLock(skynetInternetsVO.getDeviceNum());
            if(ObjectUtil.isEmpty(smartLock)){
                log.info("天网互联告警推送失败,未查询到设备号");
                return ResultBean.failedResult("失败");
            }
            if(skynetInternetsVO.getProductType()==1){
                if(skynetInternetsVO.getType()==1){
                    smartLockRepository.updateElectricQuantity(skynetInternetsVO.getBattery(),skynetInternetsVO.getDeviceNum());//同步电量
                }
                if(skynetInternetsVO.getType()==4){
                    smartLockRepository.updateElectricQuantity(Integer.parseInt(skynetInternetsVO.getBatteryInfo()),skynetInternetsVO.getDeviceNum());//同步电量
                }
                if(skynetInternetsVO.getType()==2){
                    lockAlarm.setLockId(smartLock.getId());
                    lockAlarm.setHouseId(smartLock.getHouseId());
                    lockAlarm.setSn(smartLock.getSn());
                    lockAlarm.setElectric(smartLock.getElectricQuantity());
                    lockAlarm.setAlarmTime(new Date());
                    if(skynetInternetsVO.getAlarmType()==2){//将天王互联告警类型转换为平台类型
                        lockAlarm.setAlarmType(1);
                    }
                    if(skynetInternetsVO.getAlarmType()==3){//将天王互联告警类型转换为平台类型
                        lockAlarm.setAlarmType(2);
                    }
                    lockAlarmRepository.save(lockAlarm);//添加告警
                }
            }
        }
        log.info("天网互联告警推送成功");
        return ResultBean.successfulResult("ok");
    }


    @SneakyThrows
    public ResultBean<String> warnOperate(SkynetInternetsVO skynetInternet) {
        SmartLock byMac = smartLockRepository.getSmartLock(skynetInternet.getDeviceNum());
        if(ObjectUtil.isEmpty(byMac)){
            log.info("天网互联告警推送失败,未查询到设备号");
            return ResultBean.failedResult("失败");
        }
        LockAlarm lockAlarm = new LockAlarm();
        if(skynetInternet.getProductType()==1){
            if(skynetInternet.getType()==1){
                smartLockRepository.updateElectricQuantity(skynetInternet.getBattery(),skynetInternet.getDeviceNum());//同步电量
            }
            if(skynetInternet.getType()==2){
                lockAlarm.setLockId(byMac.getId());
                lockAlarm.setHouseId(byMac.getHouseId());
                lockAlarm.setSn(byMac.getSn());
                lockAlarm.setElectric(byMac.getElectricQuantity());
                lockAlarm.setAlarmTime(new Date());
                if(skynetInternet.getAlarmType()==2){//将天王互联告警类型转换为平台类型
                    lockAlarm.setAlarmType(1);
                }
                if(skynetInternet.getAlarmType()==3){//将天王互联告警类型转换为平台类型
                    lockAlarm.setAlarmType(2);
                }
                lockAlarmRepository.save(lockAlarm);//添加告警
            }
            if(skynetInternet.getType()==4){
                SmartLockAuth identification = smartLockAuthRepository.getIdentification(skynetInternet.getIdentification());
                if(ObjectUtil.isEmpty(identification)){
                    return ResultBean.failedResult("标识错误");
                }
                LockOpenLog lockOpenLog = new LockOpenLog();
                lockOpenLog.setLockId(identification.getLockId());
                lockOpenLog.setHouseId(identification.getHouseId());
                lockOpenLogRepository.save(lockOpenLog);
                smartLockRepository.updateElectricQuantity(Integer.parseInt(skynetInternet.getBatteryInfo()),skynetInternet.getDeviceNum());//同步电量
            }
        }
        log.info("天网互联告警推送成功");
        return ResultBean.successfulResult("ok");
    }

}
